<template>
  <div class="mobile-container">
    <!-- 连接状态 -->
    <div v-if="connectionStatus === 'disconnected'" class="connection-panel">
      <h1>你画我猜 - 手机端</h1>
      <div v-if="!tvIp" class="error-message">
        <p>❌ 无效的连接链接</p>
        <p>请通过电视端的二维码扫描进入</p>
      </div>
      <div v-else class="connection-info">
        <p>正在连接到电视: {{ tvIp }}</p>
        <div class="loading-spinner"></div>
      </div>
    </div>

    <!-- 连接中状态 -->
    <div v-else-if="connectionStatus === 'connecting'" class="connection-panel">
      <h2>正在连接到电视...</h2>
      <div class="loading-spinner"></div>
    </div>

    <!-- 已连接 - 绘画界面 -->
    <div v-else-if="connectionStatus === 'connected'" class="drawing-panel">
      <div class="game-header">
        <h2>你画我猜</h2>
        <button @click="disconnect" class="disconnect-btn">断开连接</button>
      </div>
      

      <!-- 顶部工具栏 -->
      <div class="top-toolbar">
        <!-- 画笔按钮 -->
        <button 
          @click="isEraser = false"
          :class="['tool-btn', { active: !isEraser }]"
        >
          <span class="icon">✏️</span>
        </button>
        
        <!-- 橡皮擦按钮 -->
        <button 
          @click="isEraser = true"
          :class="['tool-btn', { active: isEraser }]"
        >
          <span class="icon">🧽</span>
        </button>
        
        <div class="brush-control">
          <input 
            type="range" 
            min="1" 
            max="30" 
            v-model="brushSize"
            class="brush-slider"
          >
        </div>
        
        <button 
          @click="clearCanvas"
          class="tool-btn clear-btn"
        >
          <span class="icon">🗑️</span>
        </button>
        
        <!-- 颜色选择器下拉菜单 -->
        <div class="color-picker-dropdown" ref="colorPickerRef">
          <button 
            class="color-picker-btn"
            @click.stop="showColorPicker = !showColorPicker"
          >
            <span class="icon">🎨</span>
          </button>
          <div 
            class="color-picker-menu"
            :class="{ show: showColorPicker }"
          >
            <div 
              v-for="color in colors" 
              :key="color"
              :style="{ backgroundColor: color }"
              :class="['color-option', { active: currentColor === color && !isEraser }]"
              @click="selectColor(color); showColorPicker = false"
            ></div>
          </div>
        </div>

        <!-- 表情选择器 -->
        <div class="emoji-picker-dropdown" ref="emojiPickerRef">
          <button 
            class="emoji-picker-btn"
            @click.stop="showEmojiPicker = !showEmojiPicker"
          >
            <span class="icon">😀</span>
          </button>
          <div 
            class="emoji-picker-menu"
            :class="{ show: showEmojiPicker }"
          >
            <div class="emoji-categories">
              <button 
                v-for="(category, index) in emojiCategories" 
                :key="index"
                :class="['category-btn', { active: currentEmojiCategory === index }]"
                @click="currentEmojiCategory = index"
              >
                {{ category.icon }}
              </button>
            </div>
            <div class="emoji-grid">
              <div 
                v-for="emoji in emojiCategories[currentEmojiCategory].emojis" 
                :key="emoji"
                class="emoji-option"
                @click="addEmojiToCanvas(emoji); showEmojiPicker = false"
              >
                {{ emoji }}
              </div>
            </div>
          </div>
        </div>
      </div>
      

      <!-- 画布区域 -->
      <div class="canvas-wrapper">
        <canvas 
          ref="canvas"
          class="drawing-canvas"
          @touchstart="startDrawing"
          @touchmove="draw"
          @touchend="stopDrawing"
          @mousedown="startDrawing"
          @mousemove="draw"
          @mouseup="stopDrawing"
        ></canvas>
      </div>
      
      <!-- 底部题目显示 -->
      <div class="word-display" :class="{'has-word': currentWord}">
        <h3 v-if="currentWord">请画出: {{ currentWord }}</h3>
        <h3 v-else class="waiting-text">等待TV端发送题目...</h3>
      </div>
      

      <!-- 绘画者不需要猜测功能 -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRoute } from 'vue-router';
import { onClickOutside } from '@vueuse/core';

const route = useRoute();

// 连接状态
const connectionStatus = ref<'disconnected' | 'connecting' | 'connected'>('disconnected');
let ws: WebSocket | null = null;

// 路由参数
const roomId = ref<string>('');
const tvIp = ref<string>('');

// 游戏状态
const currentWord = ref<string>(''); // 要绘画的词
const connectionTimer = ref<NodeJS.Timeout | null>(null);
const lastPingTime = ref<number>(0);

// 绘画相关
const canvas = ref<HTMLCanvasElement | null>(null);
const ctx = ref<CanvasRenderingContext2D | null>(null);
const isDrawing = ref<boolean>(false);
const lastX = ref<number>(0);
const lastY = ref<number>(0);
const currentColor = ref<string>('#000000');
const brushSize = ref<number>(5);
const isEraser = ref<boolean>(false);
const showColorPicker = ref(false);
const colorPickerRef = ref<HTMLElement | null>(null);

// 表情选择器相关
const showEmojiPicker = ref(false);
const emojiPickerRef = ref<HTMLElement | null>(null);
const currentEmojiCategory = ref(0);

onClickOutside(colorPickerRef, () => {
  showColorPicker.value = false;
});

onClickOutside(emojiPickerRef, () => {
  showEmojiPicker.value = false;
});

// 颜色选项
const colors = [
  '#000000', '#FF0000', '#00FF00', '#0000FF', 
  '#FFFF00', '#FF00FF', '#00FFFF', '#FFA500',
  '#800080', '#FFC0CB', '#A52A2A', '#808080'
];

// 表情分类数据
const emojiCategories = [
  {
    icon: '😀',
    name: '笑脸',
    emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '🤣', '😂', '🙂', '🙃', '😉', '😊', '😇', '🥰', '😍', '🤩', '😘', '😗', '😚', '😙']
  },
  {
    icon: '😢',
    name: '情感',
    emojis: ['😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', '🤐']
  },
  {
    icon: '🐶',
    name: '动物',
    emojis: ['🐶', '🐱', '🐭', '🐹', '🐰', '🦊', '🐻', '🐼', '🐨', '🐯', '🦁', '🐮', '🐷', '🐸', '🐵', '🐔', '🐧', '🐦', '🐤', '🦆']
  },
  {
    icon: '🍎',
    name: '食物',
    emojis: ['🍎', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🫐', '🍈', '🍒', '🍑', '🥭', '🍍', '🥥', '🥝', '🍅', '🍆', '🥑', '🥦', '🥒']
  },
  {
    icon: '⚽',
    name: '运动',
    emojis: ['⚽', '🏀', '🏈', '⚾', '🥎', '🎾', '🏐', '🏉', '🥏', '🎱', '🪀', '🏓', '🏸', '🏒', '🏑', '🥍', '🏏', '🪃', '🥅', '⛳']
  },
  {
    icon: '🚗',
    name: '交通',
    emojis: ['🚗', '🚕', '🚙', '🚌', '🚎', '🏎️', '🚓', '🚑', '🚒', '🚐', '🛻', '🚚', '🚛', '🚜', '🏍️', '🛵', '🚲', '🛴', '🛹', '🛼']
  }
];



/**
 * 获取设备名称
 */
const getDeviceName = (): string => {
  // 尝试从用户代理字符串中提取设备信息
  const userAgent = navigator.userAgent;
  let deviceName = '手机设备';
  
  if (userAgent.includes('iPhone')) {
    deviceName = 'iPhone';
  } else if (userAgent.includes('iPad')) {
    deviceName = 'iPad';
  } else if (userAgent.includes('Android')) {
    deviceName = 'Android设备';
  } else if (userAgent.includes('Windows')) {
    deviceName = 'Windows设备';
  } else if (userAgent.includes('Mac')) {
    deviceName = 'Mac设备';
  }
  
  // 添加时间戳以区分多个相同设备
  const timestamp = new Date().toLocaleTimeString('zh-CN', { hour12: false });
  return `${deviceName} (${timestamp})`;
};

/**
 * 初始化WebSocket连接
 */
const initConnection = async () => {
  try {
    connectionStatus.value = 'connecting';
    roomId.value = (route.query.roomId as string) || '';
    tvIp.value = (route.query.ip as string) || '';
    const port = (route.query.port as string) || '8080';

    if (!roomId.value || !tvIp.value) {
      alert('缺少必要的连接参数：roomId 或 ip');
      connectionStatus.value = 'disconnected';
      return;
    }

    // 验证IP地址格式
    const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
    if (!ipRegex.test(tvIp.value)) {
      alert(`无效的IP地址格式: ${tvIp.value}`);
      connectionStatus.value = 'disconnected';
      return;
    }

    // 验证端口号
    const portNum = parseInt(port);
    if (isNaN(portNum) || portNum < 1 || portNum > 65535) {
      alert(`无效的端口号: ${port}`);
      connectionStatus.value = 'disconnected';
      return;
    }

    const url = `ws://${tvIp.value}:${port}`;
    console.log('尝试连接WebSocket:', url);
    ws = new WebSocket(url)

    ws.onopen = () => {
      console.log('WebSocket连接已建立');
      // 发送连接消息
      const registerMsg = {
        type: 'mobile_connecting',
        roomId: roomId.value,
        deviceId: 'mobile-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now(),
        deviceName: getDeviceName(),
      };
      console.log('发送注册消息:', registerMsg);
      
      // 添加重试机制
      let retryCount = 0;
      const maxRetries = 3;
      
      const sendRegister = () => {
        if (ws && ws.readyState === WebSocket.OPEN) {
          ws.send(JSON.stringify(registerMsg));
          retryCount++;
          
          if (retryCount < maxRetries) {
            setTimeout(sendRegister, 1000);
          }
        }
      };
      
      sendRegister();
    };

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        handleSocketMessage(data);
      } catch (e) {
        console.error('解析消息失败', e);
      }
    };

    ws.onclose = (event) => {
      console.log('WebSocket连接关闭:', event.code, event.reason);
      connectionStatus.value = 'disconnected';
      ws = null;
    };

    ws.onerror = (error) => {
      console.error('WebSocket连接错误:', error);
      connectionStatus.value = 'disconnected';
      
      // 处理常见的WebSocket错误
      let errorMessage = 'WebSocket连接失败';
      if (error instanceof Event && error.target) {
        const ws = error.target as WebSocket;
        if (ws.readyState === WebSocket.CLOSED) {
          errorMessage = '无法连接到服务器，请检查IP地址和端口号是否正确';
        }
      }
      
      alert(errorMessage);
    };
  } catch (e) {
    console.error('连接失败', e);
    connectionStatus.value = 'disconnected';
  }
};

/**
 * 处理WebSocket消息
 */
const handleSocketMessage = (data: any) => {
  console.log('收到WebSocket消息:', data);
  switch (data.type) {
    case 'mobile_connected':
      console.log('手机端连接成功');
      connectionStatus.value = 'connected';
      
      // 连接成功后立即请求题目
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
          type: 'request_word',
          roomId: roomId.value
        }));
        console.log('请求题目');
      }
      break;
    case 'start_game':
      console.log('收到题目:', data.word);
      if (data.word) {
        currentWord.value = data.word;
        // 收到题目后立即发送一次画布图像
        setTimeout(() => {
          sendCanvasImage();
        }, 500);
      } else {
        currentWord.value = '未收到题目';
      }
      
      // 添加调试信息
      setTimeout(() => {
        console.log('当前题目状态:', {
          value: currentWord.value,
          element: document.querySelector('.word-display'),
          isConnected: connectionStatus.value === 'connected',
          wsState: ws?.readyState
        });
      }, 100);
      
      // 通知TV端已收到题目
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
          type: 'word_received',
          word: data.word,
          deviceId: 'mobile-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now()
        }));
      }
      break;
    case 'clear_canvas':
      clearCanvas();
      break;
    case 'error':
      console.error('服务器错误:', data.message);
      alert('连接错误: ' + data.message);
      break;
      
    case 'pong':
      lastPingTime.value = Date.now();
      break;
      
    case 'no_word':
      console.warn('TV端暂无可用题目');
      currentWord.value = '等待TV端准备题目...';
      break;
      
    case 'tv_disconnected':
      // 处理电视端断开连接
      console.log('电视端已断开连接');
      connectionStatus.value = 'disconnected';
      currentWord.value = '';
      alert('电视端已断开连接');
      break;
      
    case 'request_device_info':
      // 处理设备信息请求
      console.log('收到设备信息请求');
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({
          type: 'device_info',
          deviceId: 'mobile-' + Math.random().toString(36).substr(2, 9) + '-' + Date.now(),
          deviceName: getDeviceName(),
          deviceModel: navigator.userAgent,
          timestamp: Date.now()
        }));
        console.log('已发送设备信息');
      }
      break;
    default:
      console.log('未处理的消息类型:', data.type);
      break;
  }
};

// 移除重复的sendCanvasImage函数，使用stopDrawing中的逻辑

/**
 * 发送消息到电视端
 */
const sendMessage = (data: any) => {
  try {
    if (ws && ws.readyState === WebSocket.OPEN) {
      const messageToSend = {
        ...data,
        roomId: roomId.value,
        timestamp: Date.now()
      };
      ws.send(JSON.stringify(messageToSend));
      console.log('发送消息到电视:', messageToSend);
    } else {
      console.error('WebSocket连接未建立，无法发送消息');
    }
  } catch (error) {
    console.error('发送消息失败:', error);
  }
};



/**
 * 获取鼠标或触摸位置
 */
const getPosition = (e: TouchEvent | MouseEvent) => {
  if (!canvas.value) return { x: 0, y: 0 };
  
  const rect = canvas.value.getBoundingClientRect();
  const canvasScaleX = canvas.value.width / rect.width;
  const canvasScaleY = canvas.value.height / rect.height;

  let clientX: number, clientY: number;
  
  if (e instanceof TouchEvent) {
    const touch = e.touches[0] || e.changedTouches[0];
    if (!touch) return { x: 0, y: 0 };
    clientX = touch.clientX;
    clientY = touch.clientY;
  } else {
    clientX = e.clientX;
    clientY = e.clientY;
  }

  // 计算相对于画布的位置，考虑画布缩放
  return {
    x: (clientX - rect.left) * canvasScaleX,
    y: (clientY - rect.top) * canvasScaleY
  };
};

/**
 * 将移动端坐标转换为相对坐标 (0-1范围)
 * TV端可以根据自己的画布尺寸进行缩放
 */
const convertToRelativeCoordinates = (x: number, y: number) => {
  if (!canvas.value) return { x: 0, y: 0 };
  
  // 转换为相对坐标 (0-1范围)
  return {
    x: x / canvas.value.width,
    y: y / canvas.value.height
  };
};

/**
 * 开始绘画
 */
const startDrawing = (e: TouchEvent | MouseEvent) => {
  e.preventDefault();
  
  // 确保画布上下文存在
  if (!ctx.value || !canvas.value) {
    console.error('画布上下文不存在，无法绘图');
    return;
  }
  
  isDrawing.value = true;
  
  const pos = getPosition(e);
  lastX.value = pos.x;
  lastY.value = pos.y;
  
  // 设置绘图样式
  ctx.value.lineWidth = brushSize.value;
  ctx.value.lineCap = 'round';
  ctx.value.lineJoin = 'round';
  ctx.value.strokeStyle = currentColor.value;
  
  ctx.value.beginPath();
  ctx.value.moveTo(pos.x, pos.y);
  
  // 绘制一个点，确保即使用户只点击一下也能看到
  ctx.value.arc(pos.x, pos.y, brushSize.value / 2, 0, Math.PI * 2);
  ctx.value.fill();
  
  // 转换坐标到相对坐标系
  const relativePos = convertToRelativeCoordinates(pos.x, pos.y);
  
  // 发送绘图开始消息到TV端
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({
      type: 'draw_data',
      drawType: 'draw_start',
      relativeX: relativePos.x,
      relativeY: relativePos.y,
      color: isEraser.value ? '#FFFFFF' : currentColor.value,
      size: brushSize.value,
      isEraser: isEraser.value
    }));
  }
  
  console.log('开始绘图 - 移动端坐标:', pos.x, pos.y, '- 相对坐标:', relativePos.x, relativePos.y);
};

/**
 * 绘画过程
 */
const draw = (e: TouchEvent | MouseEvent) => {
  // 如果没有开始绘图或上下文不存在，则退出
  if (!isDrawing.value || !ctx.value || !canvas.value) return;
  
  // 阻止默认行为（如滚动）
  e.preventDefault();
  
  // 获取当前位置
  const pos = getPosition(e);
  
  // 设置绘图样式
  ctx.value.lineWidth = brushSize.value;
  ctx.value.lineCap = 'round';
  ctx.value.lineJoin = 'round';
  ctx.value.strokeStyle = isEraser.value ? '#FFFFFF' : currentColor.value;
  
  // 开始新路径
  ctx.value.beginPath();
  // 从上一个点开始
  ctx.value.moveTo(lastX.value, lastY.value);
  // 画线到当前点
  ctx.value.lineTo(pos.x, pos.y);
  // 绘制线条
  ctx.value.stroke();
  
  // 转换坐标到相对坐标系
  const relativeLastPos = convertToRelativeCoordinates(lastX.value, lastY.value);
  const relativePos = convertToRelativeCoordinates(pos.x, pos.y);
  
  // 实时发送绘图数据到TV端 - 使用节流避免发送过多消息
  if (ws && ws.readyState === WebSocket.OPEN) {
    ws.send(JSON.stringify({
      type: 'draw_data',
      drawType: 'draw_move',
      relativeLastX: relativeLastPos.x,
      relativeLastY: relativeLastPos.y,
      relativeX: relativePos.x,
      relativeY: relativePos.y,
      color: isEraser.value ? '#FFFFFF' : currentColor.value,
      size: brushSize.value,
      isEraser: isEraser.value
    }));
  }
  
  // 更新上一个点的位置
  lastX.value = pos.x;
  lastY.value = pos.y;
};

/**
 * 停止绘画
 */
const stopDrawing = () => {
  if (isDrawing.value) {
    // 转换坐标到相对坐标系
    const relativePos = convertToRelativeCoordinates(lastX.value, lastY.value);
    
    // 发送绘图结束消息到TV端
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.send(JSON.stringify({
        type: 'draw_data',
        drawType: 'draw_end',
        relativeX: relativePos.x,
        relativeY: relativePos.y,
        color: isEraser.value ? '#FFFFFF' : currentColor.value,
        size: brushSize.value,
        isEraser: isEraser.value
      }));
    }
  }
  
  isDrawing.value = false;
  // 绘图结束时发送完整图像
  sendCanvasImage();
};

/**
 * 发送画布图像到TV端
 */
const sendCanvasImage = () => {
  if (canvas.value && ws?.readyState === WebSocket.OPEN) {
    try {
      // 获取画布图像数据（压缩质量为70%）
      const imageData = canvas.value.toDataURL('image/jpeg', 0.7);
      ws.send(JSON.stringify({
        type: 'image_data',
        data: imageData,
        timestamp: Date.now()
      }));
      console.log('已发送画布图像到TV端');
    } catch (error) {
      console.error('发送画布图像失败:', error);
    }
  }
};

/**
 * 选择颜色
 */
const selectColor = (color: string) => {
  currentColor.value = color;
  isEraser.value = false;
  console.log('颜色已选择:', color);
  
  // 立即更新绘图上下文
  if (ctx.value) {
    ctx.value.strokeStyle = color;
    console.log('绘图上下文颜色已更新:', ctx.value.strokeStyle);
  }
};

/**
 * 添加表情到画布
 */
const addEmojiToCanvas = (emoji: string) => {
  if (!canvas.value || !ctx.value) {
    console.error('画布上下文不存在，无法添加表情');
    return;
  }
  
  // 在画布中心位置添加表情
  const centerX = canvas.value.width / 2;
  const centerY = canvas.value.height / 2;
  
  // 设置表情字体大小（根据画布大小调整）
  const fontSize = Math.min(canvas.value.width, canvas.value.height) * 0.1; // 画布大小的10%
  ctx.value.font = `${fontSize}px Arial`;
  ctx.value.textAlign = 'center';
  ctx.value.textBaseline = 'middle';
  
  // 绘制表情
  ctx.value.fillText(emoji, centerX, centerY);
  
  console.log('表情已添加到画布:', emoji);
  
  // 发送表情数据到TV端
  if (ws && ws.readyState === WebSocket.OPEN) {
    const relativePos = convertToRelativeCoordinates(centerX, centerY);
    ws.send(JSON.stringify({
      type: 'emoji_data',
      emoji: emoji,
      relativeX: relativePos.x,
      relativeY: relativePos.y,
      fontSize: fontSize,
      timestamp: Date.now()
    }));
    console.log('表情数据已发送到TV端');
  }
  
  // 发送完整画布图像
  setTimeout(() => {
    sendCanvasImage();
  }, 100);
};





/**
 * 清空画布
 */
const clearCanvas = () => {
  if (!canvas.value || !ctx.value) return;
  
  ctx.value.fillStyle = '#FFFFFF';
  ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height);
  
  // 通知电视端清空画布
  sendMessage({ type: 'clear_canvas' });
};

// 绘画者不需要猜测功能，移除submitGuess函数

/**
 * 断开连接
 */
const disconnect = () => {
  // 发送断开连接消息
  sendMessage({ type: 'mobile_disconnected' });
  
  // 关闭WebSocket连接
  if (ws) {
    ws.close();
    ws = null;
  }
  
  connectionStatus.value = 'disconnected';
  currentWord.value = '';
};

onMounted(() => {
  // 从URL参数获取roomId和IP地址
  roomId.value = (route.query.roomId as string) || '';
  tvIp.value = (route.query.ip as string) || '';
  
  // 若参数齐全则自动连接
  if (roomId.value && tvIp.value) {
    initConnection();
    
    // 添加连接状态监测
    connectionTimer.value = setInterval(() => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        // 每10秒发送一次ping
        if (Date.now() - lastPingTime.value > 10000) {
          ws.send(JSON.stringify({ type: 'ping' }));
          lastPingTime.value = Date.now();
        }
        
        // 如果已连接且有当前词语，定期发送画布图像（每5秒）
        if (connectionStatus.value === 'connected' && currentWord.value) {
          sendCanvasImage();
        }
        
        // 如果已连接但没有词语，请求题目
        if (connectionStatus.value === 'connected' && !currentWord.value) {
          ws.send(JSON.stringify({ 
            type: 'request_word',
            roomId: roomId.value
          }));
          console.log('请求题目');
        }
      } else if (connectionStatus.value === 'connected') {
        // 意外断开时尝试重连
        console.log('连接异常断开，尝试重新连接...');
        initConnection();
      }
    }, 5000);
  }
  
  // 设置画布大小和上下文 - 延迟执行以确保DOM已完全渲染
  setTimeout(() => {
    initCanvas();
  }, 300);
  
  // 添加窗口大小变化监听，以便在屏幕旋转或大小变化时重新调整画布
  window.addEventListener('resize', handleResize);
});

/**
 * 初始化画布 - 正方形画布
 */
const initCanvas = () => {
  if (!canvas.value) {
    console.error('画布元素不存在');
    return;
  }
  
  const container = canvas.value.parentElement;
  if (!container) {
    console.error('画布容器不存在');
    return;
  }
  
  // 设置正方形画布，与TV端保持一致
  const containerWidth = container.clientWidth - 20;
  const maxHeight = window.innerHeight * 0.5; // 最大高度为屏幕高度的50%
  
  // 使用正方形画布，取容器宽度和最大高度的较小值
  const canvasSize = Math.min(containerWidth, maxHeight);
  
  // 设置画布为正方形
  canvas.value.width = canvasSize;
  canvas.value.height = canvasSize;
  
  // 获取2D上下文
  ctx.value = canvas.value.getContext('2d');
  
  if (!ctx.value) {
    console.error('无法获取画布上下文');
    return;
  }
  
  console.log('移动端正方形画布初始化成功，大小:', canvas.value.width, 'x', canvas.value.height);
  console.log('容器宽度:', containerWidth, '最大高度:', maxHeight);
  
  // 初始化白色背景
  ctx.value.fillStyle = '#FFFFFF';
  ctx.value.fillRect(0, 0, canvas.value.width, canvas.value.height);
};

/**
 * 处理窗口大小变化
 */
const handleResize = () => {
  // 重新初始化画布大小
  initCanvas();
};

onBeforeUnmount(() => {
  // 关闭WebSocket连接
  if (ws) {
    ws.close();
    ws = null;
  }
  
  // 清除定时器
  if (connectionTimer.value) {
    clearInterval(connectionTimer.value);
    connectionTimer.value = null;
  }
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize);
  
  console.log('组件卸载，资源已清理');
});
</script>

<style scoped lang="scss">
@use '../assets/styles/drawguess-mobile.scss';
</style>
